package org.jash.shop2112.category

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Route
import org.jash.shop2112.BR
import org.jash.shop2112.R
import org.jash.shop2112.databinding.FragmentCategoryBinding
import org.jash.shop2112.entity.Category
import org.jash.shop2112.entity.Goods
import org.jash.shop2112.mvvm.BaseFragment
import org.jash.shop2112.utils.CommonAdapter
import org.jash.shop2112.utils.Event


@Route(path ="/shop/category")
class CategoryFragment : BaseFragment<FragmentCategoryBinding, CategoryViewModel>() {
    private val categoryAdapter by lazy { CommonAdapter<Category>({R.layout.category_item to BR.category }) }
    private val subCategoryAdapter by lazy { CommonAdapter<Category>({R.layout.sub_category_item to BR.category }) }
    private val productAdapter by lazy { CommonAdapter<Goods>({R.layout.goods_item to BR.goods})}
    private var cid = 0
    private var page = 1
    private val size = 10
    override fun initData() {
        viewModel.goodsLiveData.observe(viewLifecycleOwner) {
            if (page == 1) {
                productAdapter.clear()
            }
            productAdapter += it
            binding.refresh.closeHeaderOrFooter()
        }
        viewModel.categoryLiveData.observe(viewLifecycleOwner) {
            categoryAdapter += it
            if (it.isNotEmpty()) {
                it[0].showSubCategory()
            }
        }
        viewModel.loadCategory()
    }

    override fun error(throwable: Throwable) {
        super.error(throwable)
        binding.refresh.closeHeaderOrFooter()
    }
    override fun initView() {
        binding.mainCategory.adapter = categoryAdapter
        binding.subCategory.adapter = subCategoryAdapter
        binding.product.adapter = productAdapter
        binding.refresh.setOnRefreshListener {
            page = 1
            viewModel.loadGoods(cid, page, size)
        }
        binding.refresh.setOnLoadMoreListener {
            page++
            viewModel.loadGoods(cid, page, size)
        }
    }
    @Event("showSubCategory")
    fun loadSubCategory(categories:List<Category>) {
        subCategoryAdapter.clear()
        productAdapter.clear()
        subCategoryAdapter += categories
        if (categories.isNotEmpty()) {
            categories[0].showProduct()
        }
    }
    @Event("showProduct")
    fun loadProduct(id:Int) {
        cid = id
        page = 1
        viewModel.loadGoods(cid, page, size)
    }
}